package org.example.common.config;

import org.example.common.model.Book;
import org.example.request.BookRequest;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 工厂模式获取Book对象
 */
public class DefaultBookFactory {
    private final ConcurrentHashMap<Long, Book> bookStore = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1000);
    private static final DefaultBookFactory instance = new DefaultBookFactory();
    public static DefaultBookFactory getInstance() { return instance; }
    private DefaultBookFactory() {}

    private static final List<Book> books = new ArrayList<>();

    public Long createBook(BookRequest request) {
        long id = idGenerator.incrementAndGet();
        Book book = new Book(
                id,
                request.getTitle(),
                request.getAuthor(),
                LocalDateTime.now(),
                LocalDateTime.now()
        );
        bookStore.put(id, book);
        return id;
    }

    public Book findById(Long id) {
        return bookStore.get(id);
    }

    public void updateById(Long id, BookRequest request) {
        Book book = bookStore.get(id);
        book.setTitle(request.getTitle());
        book.setAuthor(request.getAuthor());
        book.setUpdateTime(LocalDateTime.now());
        bookStore.put(id, book);
    }

    public void deleteById(Long id) {
        bookStore.remove(id);
    }

    public void deleteAll() {
        bookStore.clear();
    }
}